//
//  MainSearchViewController.m
//  InviteJob
//
//  Created by chirui on 2017/10/31.
//  Copyright © 2017年 Shui. All rights reserved.
//

#import "MainSearchViewController.h"
#import "MainTableViewCell.h"
#import "ImageTextButton.h"
#import "BuilsServerDetailsViewController.h"

@interface MainSearchViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>{
    
    UITextField * searchText;
    UITableView * _tableView;
    ImageTextButton * typeBtn;
    NSString * typeStr;
    
    NSMutableArray * _dataArray;
    
    
    int _page;
    int _totailPage;
    UIView * noBodyView;
    
    NSString * keywordStr;
    
}

@end

@implementation MainSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    typeStr = @"";
    _page = 1;
    
    keywordStr = @"";
    _dataArray = @[].mutableCopy;
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem rightItemWithTitle:@"搜索"  target:self action:@selector(searchClick:)];
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"icon_nav_publie_return" target:self action:@selector(backClick)];
    
    UIView * searchView =[[UIView alloc]initWithFrame:CGRectMake(30, -3, WIDTH - 100, 30)];
    searchView.layer.cornerRadius = 15.f;
    searchView.layer.masksToBounds = YES;
    
    searchView.backgroundColor = RGB(0x00a8da);
    
    
    typeBtn = [[ImageTextButton alloc] initWithFrame:CGRectMake(10, 0, 70,30)
                                                      image:[UIImage imageNamed:@"icon_nav_drop_down"]
                                                      title:@"服务类型"];
    typeBtn.buttonTitleWithImageAlignment = UIButtonTitleWithImageAlignmentRight;
    typeBtn.titleLabel.font =[UIFont systemFontOfSize:14];
    [typeBtn addTarget:self action:@selector(typeBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [searchView addSubview:typeBtn];
    
    UIView * lineView =[[UIView alloc]initWithFrame:CGRectMake(83, 10, 1, 10)];
    lineView.backgroundColor =strColor(@"f6f6f6");
    [searchView addSubview:lineView];
    
    searchText =[[UITextField alloc]initWithFrame:CGRectMake(90, 0, CGRectGetWidth(searchView.frame)-90, 30)];
    
    searchText.font =[UIFont systemFontOfSize:14];
    searchText.delegate = self;
    searchText.textColor =[UIColor whiteColor];
    searchText.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"关键字" attributes:@{NSForegroundColorAttributeName: [UIColor whiteColor]}];
    [searchView addSubview:searchText];
    
    self.navigationItem.titleView = searchView;
    
    
    
//    noBodyView = [NothingMessageView creatNothingMessageViewFrame:CGRectMake(WIDTH/2-100, (HEIGHT-64)/2-150, 200, 200) andMessageStr:@"没有相关信息！" onView:nil];
    
    [self getMessageListData];
}

-(void)backClick{

    [self.navigationController popViewControllerAnimated:YES];
}

-(void)typeBtnClick{
    
    
    NSArray *  titleArray = @[@"施工队",@"投标融资",@"设计外包",@"造价资料",
                              @"办营资安",@"证才中介",@"公司转让",@"教育培训",
                              @"建材供应",@"机械供应",@"二手租赁",@"房屋出租",
                              @"税法法务",@"维管后勤",@"特殊其他"];
    zySheetPickerView * pickerView = [zySheetPickerView ZYSheetStringPickerWithTitle:titleArray andHeadTitle:@"服务类型" Andcall:^(zySheetPickerView *pickerView, NSString *choiceString) {
        
        [typeBtn setTitle:choiceString forState:UIControlStateNormal];
        typeStr = choiceString;
        
        _page = 1;
        [self getMessageListData];
        
        [pickerView dismissPicker];
    }];
    [pickerView show];
    
//    UIWindow *window = [[UIApplication sharedApplication].delegate window];
//    
//    bgView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
//    bgView.backgroundColor = ColorA(0, 0, 0, 0.5);
//    
//    UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 65, 36, 9)];
//    imageView.image = ImageName(@"icon_search_arrow");
//    [bgView addSubview:imageView];
//    
//    UIView * btnView =[[UIView alloc]initWithFrame:CGRectMake(50, 74,100, 160)];
//    btnView.backgroundColor = NavBackColor;
//    btnView.layer.cornerRadius = 5.f;
//    btnView.layer.masksToBounds = YES;
//    UIView * line =[[UIView alloc]initWithFrame:CGRectMake(10, 40, 80, 0.5)];
//    line.backgroundColor =[UIColor whiteColor];
//    [btnView addSubview:line];
//    
//    UIView * line_two =[[UIView alloc]initWithFrame:CGRectMake(10, 80, 80, 0.5)];
//    line_two.backgroundColor =[UIColor whiteColor];
//    [btnView addSubview:line_two];
//    
//    UIView * line_three =[[UIView alloc]initWithFrame:CGRectMake(10, 120, 80, 0.5)];
//    line_three.backgroundColor =[UIColor whiteColor];
//    [btnView addSubview:line_three];
//    
//    [bgView tapAction:^{
//        
//        [bgView removeFromSuperview];
//    }];
//    
//    
//    [self creatBtnFrame:CGRectMake(0, 0, 100, 40) andTitle:@"服务类型" andSel:@selector(chooseDoctorBtnClick:) onView:btnView];
//    
//    [self creatBtnFrame:CGRectMake(0, 40, 100, 40) andTitle:@"服务类型" andSel:@selector(chooseNewsBtnClick:) onView:btnView];
//    
//    [self creatBtnFrame:CGRectMake(0, 80, 100, 40) andTitle:@"服务类型" andSel:@selector(chooseNewsBtnClick:) onView:btnView];
//    
//    [self creatBtnFrame:CGRectMake(0, 120, 100, 40) andTitle:@"服务类型" andSel:@selector(chooseNewsBtnClick:) onView:btnView];
//    
//    
//    
//    [bgView addSubview:btnView];
//    
//    [window addSubview:bgView];
    
}

-(void)creatBtnFrame:(CGRect)rec andTitle:(NSString *)title andSel:(SEL)sel onView:(UIView *)view {
    
    UIButton * chooseDoctor =[UIButton buttonWithType:UIButtonTypeSystem];
    chooseDoctor.frame = rec;
    chooseDoctor.backgroundColor =[UIColor clearColor];
    [chooseDoctor setTitle:title forState:UIControlStateNormal];
    [chooseDoctor setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    chooseDoctor.titleLabel.font =[UIFont systemFontOfSize:14];
    [chooseDoctor addTarget:self action:sel forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:chooseDoctor];
    
}

-(void)searchClick:(UIButton *)btn {
    
    [searchText resignFirstResponder];
    
    if (searchText.text.length==0||searchText.text==nil) {
        
//        SHuiMBhudTextTimeStr(@"请输入关键字搜索");
        
        return;
    }
    [self creatTableView];
    _page = 1;
    keywordStr = searchText.text;
    
    [self getMessageListData];
    
}

-(void)creatTableView {
    
    _tableView =[[UITableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-64) style:UITableViewStyleGrouped];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    UIView * view =[[UIView alloc]init];
    _tableView.tableFooterView = view;
    [self.view addSubview:_tableView];
    
    [_tableView registerNib:[UINib nibWithNibName:[MainTableViewCell reuseIdentifier] bundle:nil] forCellReuseIdentifier:[MainTableViewCell reuseIdentifier]];
    

    
    MJRefreshNormalHeader * header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        _page = 1;
        
        [self getMessageListData];
    }];
    _tableView.mj_header = header;
    
    
    MJRefreshAutoNormalFooter *  footer =[MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _page++;
        [self getMessageListData];
    }];
    
    footer.automaticallyRefresh = YES;
    _tableView.mj_footer =footer;
    _tableView.mj_footer.hidden = NO;
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    
    return _dataArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSDictionary * dic = _dataArray[indexPath.row];
    UILabel * contLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, 70, WIDTH -40, 20)];
    contLabel.text  = dic[@"title"];
    contLabel.font =[UIFont systemFontOfSize:15];
    contLabel.numberOfLines = 0;
    [contLabel sizeToFit];
    
//    UIImageView * imageView;
//    NSArray * imageArray;
//    
//    if ([dic[@"img_srcs"] isKindOfClass:[NSArray class]]) {
//        
//        imageArray = dic[@"img_srcs"];
//        
//        if (imageArray.count>3) {
//            for (int i=0; i<3; i++) {
//                
//                imageView =[[UIImageView alloc]initWithFrame:CGRectMake(20+10*i+(WIDTH-60)/3*i, CGRectGetMaxY(contLabel.frame)+10, (WIDTH-60)/3, (WIDTH-60)/3)];
//                [imageView sd_setImageWithURL:ImageUrl(imageArray[i]) placeholderImage:ImageName(@"img_dynamic_1")];
//            }
//        }else{
//            
//            for (int i=0; i<imageArray.count; i++) {
//                
//                imageView =[[UIImageView alloc]initWithFrame:CGRectMake(20+10*i+(WIDTH-60)/3*i, CGRectGetMaxY(contLabel.frame)+10, (WIDTH-60)/3, (WIDTH-60)/3)];
//                [imageView sd_setImageWithURL:ImageUrl(imageArray[i]) placeholderImage:ImageName(@"img_dynamic_1")];
//            }
//        }
//    }
//    
//    if (imageArray.count ==0) {
    
        return CGRectGetMaxY(contLabel.frame)+20;
        
//    }else {
//        
//        return CGRectGetMaxY(imageView.frame)+20;
//    }

}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 0.01;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString * iden = @"cellid";
    UITableViewCell * cell =[tableView dequeueReusableCellWithIdentifier:iden];
    if (!cell) {
        cell =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:iden];
    }else{
        while ([cell.contentView.subviews lastObject] != nil) {
            
            [(UIView *)[cell.contentView.subviews lastObject] removeFromSuperview];
        }
    }
    
    NSDictionary * dic = _dataArray[indexPath.row];
    UIView * bgView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 70)];
    bgView.backgroundColor =[UIColor whiteColor];
    
    UIImageView * userIcon =[[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 50, 50)];
    
    [userIcon sd_setImageWithURL:ImageUrl(dic[@"avatar"]) placeholderImage:ImageName(@"img_default_head")];
    userIcon.layer.cornerRadius = 25.f;
    userIcon.layer.masksToBounds =YES;
    [bgView addSubview:userIcon];
    
    
    UILabel * nameLabel =[[UILabel alloc]initWithFrame:CGRectMake(70, 13, WIDTH - 90, 20)];
    nameLabel.font =[UIFont boldSystemFontOfSize:15];
    nameLabel.textColor = RGB(0x333333);
    nameLabel.text = dic[@"user_name"];
    [bgView addSubview:nameLabel];
    
    UILabel * timeLabel =[[UILabel alloc]initWithFrame:CGRectMake(70, 40, WIDTH -90, 20)];
    timeLabel.font =[UIFont systemFontOfSize:13];
    timeLabel.textColor = [UIColor grayColor];
    timeLabel.text = dic[@"update_time"];
    [bgView addSubview:timeLabel];
    
    UILabel * kindLabel =[[UILabel alloc]initWithFrame:CGRectMake(WIDTH-80, 13, 65, 30)];
    kindLabel.font =[UIFont systemFontOfSize:13];
    kindLabel.textColor = strColor(@"ff7800");
    kindLabel.text = dic[@"service_type"];
    kindLabel.textAlignment = NSTextAlignmentCenter;
    kindLabel.layer.cornerRadius = 3;
    kindLabel.layer.borderWidth = 0.5;
    kindLabel.layer.borderColor = strColor(@"ff7800").CGColor;
    [bgView addSubview:kindLabel];
    
    
    UILabel * contLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, CGRectGetMaxY(userIcon.frame)+10, WIDTH -40, 20)];
    
    if ([USER_DEFAULTGet(@"server") isEqualToString:@"project"]) {
        contLabel.text  = [NSString stringWithFormat:@"业务需求：%@",dic[@"title"]];
    }else{
        contLabel.text  = [NSString stringWithFormat:@"业务范围：%@",dic[@"title"]];
    }
    contLabel.font =[UIFont systemFontOfSize:15];
    contLabel.numberOfLines = 0;
    [contLabel sizeToFit];
    [bgView addSubview:contLabel];
    
    //    UIImageView * imageView;
    //    NSArray * imageArray;
    //
    //    if ([dic[@"img_srcs"] isKindOfClass:[NSArray class]]) {
    //
    //        imageArray = dic[@"img_srcs"];
    //        if (imageArray.count>3) {
    //
    //        for (int i=0; i<3; i++) {
    //
    //            imageView =[[UIImageView alloc]initWithFrame:CGRectMake(20+10*i+(WIDTH-60)/3*i, CGRectGetMaxY(contLabel.frame)+10, (WIDTH-60)/3, (WIDTH-60)/3)];
    //            [imageView sd_setImageWithURL:ImageUrl(imageArray[i]) placeholderImage:ImageName(@"img_dynamic_1")];
    //            imageView.contentMode = UIViewContentModeScaleAspectFill;
    //            imageView.clipsToBounds = YES;
    //            [bgView addSubview:imageView];
    //        }
    //        }else {
    //            for (int i=0; i<imageArray.count; i++) {
    //
    //                imageView =[[UIImageView alloc]initWithFrame:CGRectMake(20+10*i+(WIDTH-60)/3*i, CGRectGetMaxY(contLabel.frame)+10, (WIDTH-60)/3, (WIDTH-60)/3)];
    //                [imageView sd_setImageWithURL:ImageUrl(imageArray[i]) placeholderImage:ImageName(@"img_dynamic_1")];
    //                imageView.contentMode = UIViewContentModeScaleAspectFill;
    //                imageView.clipsToBounds = YES;
    //                [bgView addSubview:imageView];
    //         }
    //        }
    //    }
    //
    //    if (imageArray.count==0) {
    bgView.frame = CGRectMake(0, 0, WIDTH, CGRectGetMaxY(contLabel.frame)+20);
    
    //    }else {
    //
    //      bgView.frame = CGRectMake(0, 0, WIDTH, CGRectGetMaxY(imageView.frame)+20);
    //    }
    
    
    
    UIView * lineView =[[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(bgView.frame)-10, WIDTH, 10)];
    lineView.backgroundColor =strColor(@"f6f6f6");
    [bgView addSubview:lineView];
    
    [cell.contentView addSubview:bgView];
    return cell;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary * dic = _dataArray[indexPath.row];
    BuilsServerDetailsViewController * details =[[BuilsServerDetailsViewController alloc]init];
    details.hidesBottomBarWhenPushed = YES;
    details.severID = dic[@"service_id"];
    [self.navigationController pushViewController:details animated:YES];
    
    
}

-(void)getMessageListData{
    
    if (_totailPage != 0) {
        if(_page == _totailPage + 1){
            [_tableView.mj_footer setState: MJRefreshStateNoMoreData];
            
            return ;
        }
    }
    NSDictionary * dic = @{@"page":[NSString stringWithFormat:@"%d",_page],
                           @"perpage":@"10",
                           @"code":@"",
                           @"service_type":typeStr,
                           @"title":keywordStr,
                           @"type":USER_DEFAULTGet(@"server")};
    
    SHuiMBhubNoTimeStr(@"正在加载...");
    [PostNetWorking postNetWorkingStr:RequestUrlStr(BuildService_list_api) andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;
        if (codeSucess) {
            _totailPage = [responseObject[@"datas"][@"total_page"]  intValue];
            
            if (_page==1) {
                
                if (_dataArray) {
                    
                    [_dataArray removeAllObjects];
                }
                if ([responseObject[@"datas"][@"lists"]  isKindOfClass:[NSArray class]]) {
                    
                    for (NSDictionary * dic in responseObject[@"datas"][@"lists"]) {
                        
                        [_dataArray addObject:dic];
                    }
                }
            }else {
                
                if ([responseObject[@"datas"][@"lists"]  isKindOfClass:[NSArray class]]) {
                    
                    for (NSDictionary * dic in responseObject[@"datas"][@"lists"]) {
                        
                        [_dataArray addObject:dic];
                    }
                }
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                
                
                if (_dataArray.count>0) {
                    [self hideNoDataView];
//                    noBodyView.hidden = YES;
                    if (_dataArray.count<10) {
                        
                        _tableView.mj_footer.hidden = YES;
                    }else {
                        _tableView.mj_footer.hidden = NO;
                    }
                }else {
                    _tableView.mj_footer.hidden = YES;
                    [self shopNoDataViewBackgroundColor:[UIColor clearColor] withImage:@"img_home_no_news" withLabelMsg:@"没有任何数据" withButton:@"" isY:0];
//                     noBodyView.hidden = NO;
//                     [self.view addSubview:noBodyView];
                }
                [_tableView.mj_header endRefreshing];
                [_tableView.mj_footer endRefreshing];
                [_tableView reloadData];
                
            });
            
        }else {
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        
    } failed:^(NSError *error) {
        SHuiMBHidleYes;
        SHuiMBhudTextTimeStr(@"网络错误请重试！");
    }];
    
    
}



@end
